#target "indesign"

/*
    扫描指定文件夹中的 InDesign 文档，如果文档中包含指定链接图片，则将文档路径写入用户选择目录下的 LinkedFiles.txt。
*/
(function () {
    var folderResult = obtainTargetFolder();
    if (!folderResult.ok) {
        if (folderResult.message) {
            alert(folderResult.message);
        }
        return;
    }
    var targetFolder = folderResult.folder;

    var linkedFile = File.openDialog("请选择要检测的链接图片：", "*.*");
    if (!linkedFile) {
        alert("未选择链接图片，脚本结束。");
        return;
    }
    if (!linkedFile.exists) {
        alert("所选链接图片不存在，脚本结束。");
        return;
    }

    var includeSubfolders = confirm("是否扫描所有子文件夹？\n选择“是”扫描所有子文件夹，选择“否”仅扫描当前文件夹。");

    var outputFolder = Folder.selectDialog("请选择保存 LinkedFiles.txt 的目录：");
    if (!outputFolder) {
        alert("未选择输出目录，脚本结束。");
        return;
    }

    var canSetInteraction = typeof UserInteractionLevels !== "undefined";
    var originalInteraction = canSetInteraction ? app.scriptPreferences.userInteractionLevel : null;
    var canUseDialogModes = typeof app.displayDialogs !== "undefined" && typeof DialogModes !== "undefined";
    var originalDisplayDialogs = canUseDialogModes ? app.displayDialogs : null;

    try {
        if (canSetInteraction) {
            app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
        }
        if (canUseDialogModes) {
            app.displayDialogs = DialogModes.NO;
        }

        var inddFiles = [];
        collectInddFiles(targetFolder, inddFiles, includeSubfolders);
        if (!inddFiles.length) {
            alert("目标文件夹及其子文件夹中未找到 InDesign 文档。");
            return;
        }

        var isWindows = File.fs === "Windows";
        var targetFsPath = linkedFile.fsName;
        if (isWindows) {
            targetFsPath = targetFsPath.toLowerCase();
        }

        var matchingDocs = [];
        for (var i = 0; i < inddFiles.length; i++) {
            var docFile = inddFiles[i];
            if (!docFile.exists) {
                continue;
            }

            var doc = findOpenDocument(docFile.fsName);
            var openedHere = false;
            if (!doc) {
                try {
                    doc = app.open(docFile, false);
                    openedHere = true;
                } catch (openErr) {
                    $.writeln("无法打开文档：" + docFile.fsName + "；原因：" + openErr);
                    continue;
                }
            }

            try {
                if (documentContainsLink(doc, targetFsPath, isWindows)) {
                    matchingDocs.push(docFile.fsName);
                }
            } catch (inspectErr) {
                $.writeln("检测文档时出错：" + docFile.fsName + "；原因：" + inspectErr);
            } finally {
                if (openedHere && doc && doc.isValid) {
                    doc.close(SaveOptions.NO);
                }
            }
        }

        var outputFile = new File(outputFolder.fsName + "/LinkedFiles.txt");
        outputFile.encoding = "UTF-8";
        outputFile.lineFeed = "Windows";
        if (!outputFile.open("w")) {
            alert("无法创建输出文件：" + outputFile.fsName);
            return;
        }
        outputFile.write("\uFEFF");
        for (var j = 0; j < matchingDocs.length; j++) {
            outputFile.writeln(matchingDocs[j]);
        }
        outputFile.close();

        if (matchingDocs.length) {
            alert("检测完成，共找到 " + matchingDocs.length + " 个文档。结果已写入：" + outputFile.fsName);
        } else {
            alert("未找到包含指定链接图片的文档。已创建空的 LinkedFiles.txt。");
        }
    } catch (runtimeErr) {
        alert("脚本运行过程中发生错误：" + runtimeErr);
    } finally {
        if (canSetInteraction) {
            app.scriptPreferences.userInteractionLevel = originalInteraction;
        }
        if (canUseDialogModes) {
            app.displayDialogs = originalDisplayDialogs;
        }
    }

    function collectInddFiles(folder, bucket, includeChildren) {
        var entries = folder.getFiles();
        for (var idx = 0; idx < entries.length; idx++) {
            var entry = entries[idx];
            if (entry instanceof Folder) {
                if (includeChildren) {
                    collectInddFiles(entry, bucket, true);
                }
            } else if (entry instanceof File && /\.indd$/i.test(entry.name)) {
                bucket.push(entry);
            }
        }
    }

    function findOpenDocument(fsName) {
        for (var idx = 0; idx < app.documents.length; idx++) {
            var openDoc = app.documents[idx];
            try {
                if (!openDoc.isValid) {
                    continue;
                }
                var fullName = openDoc.fullName;
                if (fullName && fullName.fsName === fsName) {
                    return openDoc;
                }
            } catch (err) {
                // 忽略未保存文档或其他异常
            }
        }
        return null;
    }

    function documentContainsLink(doc, targetPath, normalizeToLowerCase) {
        var links = doc.links;
        if (!links || !links.length) {
            return false;
        }
        for (var l = 0; l < links.length; l++) {
            var linkPath = resolveLinkPath(links[l]);
            if (!linkPath) {
                continue;
            }
            if (normalizeToLowerCase) {
                if (linkPath.toLowerCase() === targetPath) {
                    return true;
                }
            } else if (linkPath === targetPath) {
                return true;
            }
        }
        return false;
    }

    function resolveLinkPath(link) {
        if (!link || !link.isValid) {
            return null;
        }
        try {
            if (link.filePath) {
                return File(link.filePath).fsName;
            }
        } catch (err1) {
            // 忽略，尝试备用方案
        }
        try {
            if (link.assetURL) {
                var uri = decodeURI(link.assetURL);
                if (uri.indexOf("file://") === 0) {
                    uri = uri.replace("file://", "");
                }
                return File(uri).fsName;
            }
        } catch (err2) {
            // 忽略
        }
        return null;
    }

    function obtainTargetFolder() {
        var manualFolder = confirm("是否手动输入包含 InDesign 文档的文件夹路径？\n选择“是”手动输入路径，选择“否”通过窗口选择。");
        if (manualFolder) {
            var folderInput = prompt("请输入文件夹路径，例如：\n\"Z:\\文件夹\"\nZ:\\文件夹", "");
            var normalizedPath = extractFolderPath(folderInput);
            if (!normalizedPath) {
                return { ok: false, message: "未输入有效的文件夹路径，脚本结束。" };
            }
            var folder = new Folder(normalizedPath);
            if (!folder.exists) {
                return { ok: false, message: "输入的文件夹不存在：" + normalizedPath };
            }
            return { ok: true, folder: folder };
        }
        var selectedFolder = Folder.selectDialog("请选择包含 InDesign 文档的文件夹：");
        if (!selectedFolder) {
            return { ok: false, message: "未选择文件夹，脚本结束。" };
        }
        return { ok: true, folder: selectedFolder };
    }

    function extractFolderPath(input) {
        if (input === null || input === undefined) {
            return "";
        }
        var lines = String(input).split(/[\r\n]+/);
        var candidate = "";
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i].replace(/^\s+|\s+$/g, "");
            if (line.length > 0) {
                candidate = line;
                break;
            }
        }
        if (!candidate.length) {
            return "";
        }
        if (candidate.charAt(0) === "\"" && candidate.charAt(candidate.length - 1) === "\"") {
            candidate = candidate.substring(1, candidate.length - 1);
        }
        return candidate;
    }
})();
